// pages/backApplication/backApplication.js
var util = require("../../utils/util.js");
const APP = getApp()
const app = getApp()
const Utils = require('../../utils/uti.js')

Page({


  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    hasUserInfo: false,
    // whether to disable join btn or not
    disableJoin: false,
    show10: false,
    pageNum: 1,
    pageSize: 4,
    ress: '',
    timeRangeSelecter: [], //  可选时间范围数组
    daySelecter: [], //可选日期数组
    yuyueForm: {
      timeDateStr: '', //时间段
      timeDate: '', //日期
    },
    timeActiveIndex: -1, //时间选择下标
    current: 0, //步骤条下标
    option1: [{
        text: '最新申请',
        value: 0
      },
      {
        text: '一周前',
        value: 1
      },
      {
        text: '半月前',
        value: 2
      },
      {
        text: '一月前',
        value: 3
      },
    ],
    itemTitle: '选择日期',
    value1: 0,
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    showTime: false,
    roomList: [],
    navList: [],
    sh: false,
    show: false,
    showroom: false,
    quxiao: false,
    title: '',
    que: false,
    jujue: false,


    openPic: false, //是否显示证件照片
  },
  // 显示证件照片
  openShowPic() {
    let openPic = this.data.openPic
    this.setData({
      openPic: !openPic
    })
  },
  tolook() {
    // wx.navigateTo({
    //   url: '/pages/loginMeeting/loginMeeting'
    // })
    this.setData({
      show10: true
    });
  },
  onClose10() {
    this.setData({
      show10: false,
      room: ""

    });
  },
  onChange10(e) {
    this.setData({
      room: e.detail,
    });

  },
  // onCloseroom(){
  //   this.setData({
  //     room: "",
  //   });
  // },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.channel = "";
    this.uid = Utils.getUid();
    this.lock = false;
    let userInfo = wx.getStorageSync("userInfo");
    if (userInfo) {
      this.setData({
        hasUserInfo: true,
        userInfo: userInfo
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this

    this.channel = "";
    this.uid = Utils.getUid();
    this.lock = false;
    let userInfo = wx.getStorageSync("userInfo");
    this.setData({
      navList: [],
      pageNum: 1,
    })
    this.getList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that = this
    that.setData({
      pageNum: that.data.pageNum + 1
    })
    this.getList();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {


  },
  //监听事件
  reason: function (e) {

    this.setData({
      ['form.reason']: e.detail
    });

  },
  //初始信息

  getList: function () {

    var list = {
      url: '/system/subscribe/queryList?pageNum=' + this.data.pageNum + '&pageSize=' + this.data.pageSize,
      method: 'get',
      data: this.data.paramas
    }
    APP.request.backWxRequest(list).then(res => {
      var navList = this.data.navList
      var rows = res.data.rows
      var allArr = [...navList, ...rows]
      if (res.data.code === 200) {
        this.setData({
          navList: allArr
        })
      }
    })

  },
  // 选择时间
  onInput(event) {
    this.setData({
      currentDate: event.detail,
    });
  },
  //选择房间
  room() {
    this.setData({
      show: false,
      showroom: true
    })
  },
  onroom(event) {
    console.log(event.detail)
    this.setData({
      ['form.room']: event.detail.value,
      show: true,
      showroom: false,
    })
  },
  closeroom() {
    this.setData({
      show: true,
      showroom: false,

    })
  },
  pizhun(e) {
    this.setData({
      ress: "备注信息",
      que: true,
      sh: false,
      quxiao: false,
      jujue: false,
      paramas: [],
      show: true,
      title: "批准申请",
      paramas: {
        subscribeId: e.currentTarget.dataset.subscribeid
      }
    })
    var personList = {
      url: '/system/subscribe/queryList',
      method: 'get',
      data: this.data.paramas
    }
    APP.request.backWxRequest(personList).then(res => {
      if (res.data.code === 200) {
        if (!!res.data.rows[0].office) res.data.rows[0].office = util.config().api + res.data.rows[0].office
        if (!!res.data.rows[0].attorney) res.data.rows[0].attorney = util.config().api + res.data.rows[0].attorney
        if (!!res.data.rows[0].backImage) res.data.rows[0].backImage = util.config().api + res.data.rows[0].backImage
        if (!!res.data.rows[0].frontImage) res.data.rows[0].frontImage = util.config().api + res.data.rows[0].frontImage
        if (!!res.data.rows[0].lawyerImage) res.data.rows[0].lawyerImage = util.config().api + res.data.rows[0].lawyerImage
        this.setData({
          form: res.data.rows[0],
          'form.reason': '',
        });
        console.log('批准申请', res.data.rows[0]);

        var list = {
          url: '/system/subscribe/getRoom/?deptId=' + this.data.form.deptId,
          method: 'get',

        }
        APP.request.backWxRequest(list).then(res => {
          if (res.data.code === 200) {
            this.setData({
              roomList: res.data.data
            })
          }
        })

      }
    });
  },
  jujue(e) {
    this.setData({

      ress: "拒绝原因",
      sh: false,
      jujue: true,
      que: false,
      quxiao: false,
      show: true,
      title: "拒绝申请",
      paramas: {
        subscribeId: e.currentTarget.dataset.subscribeid
      }
    })
    var personList = {
      url: '/system/subscribe/queryList',
      method: 'get',
      data: this.data.paramas
    }
    APP.request.backWxRequest(personList).then(res => {
      if (res.data.code === 200) {
        this.setData({
          form: res.data.rows[0],
          'form.reason': '',
        });

      }
    });
  },
  shenqing(e) {
    this.setData({
      ress: "修改原因",
      sh: true,
      que: false,
      jujue: false,
      show: true,
      title: "申请修改",
      paramas: {
        subscribeId: e.currentTarget.dataset.subscribeid
      }
    })
    var personList = {
      url: '/system/subscribe/queryList',
      method: 'get',
      data: this.data.paramas
    }
    APP.request.backWxRequest(personList).then(res => {
      if (res.data.code === 200) {
        if (!!res.data.rows[0].office) res.data.rows[0].office = util.config().api + res.data.rows[0].office
        if (!!res.data.rows[0].attorney) res.data.rows[0].attorney = util.config().api + res.data.rows[0].attorney
        if (!!res.data.rows[0].backImage) res.data.rows[0].backImage = util.config().api + res.data.rows[0].backImage
        if (!!res.data.rows[0].frontImage) res.data.rows[0].frontImage = util.config().api + res.data.rows[0].frontImage
        if (!!res.data.rows[0].lawyerImage) res.data.rows[0].lawyerImage = util.config().api + res.data.rows[0].lawyerImage
        console.log('申请', res.data.rows[0]);

        this.setData({
          form: res.data.rows[0],
          'form.reason': '',
        });

        var timeList = {
          url: '/system/subscribe/getTime/list',
          method: 'get',
        }
        APP.request.backWxRequest(timeList).then(res => {
          if (res.data.code === 200) {
            var daySelecter = res.data.data
            this.setData({
              daySelecter: daySelecter
            })
          }

        })

      }
    });
  },
  quxiao(e) {
    this.setData({

      ress: "取消原因",
      sh: false,
      quxiao: true,
      que: false,
      jujue: false,
      show: true,
      title: "取消",
      paramas: {
        subscribeId: e.currentTarget.dataset.subscribeid
      }
    })
    var personList = {
      url: '/system/subscribe/queryList',
      method: 'get',
      data: this.data.paramas
    }
    APP.request.backWxRequest(personList).then(res => {
      if (res.data.code === 200) {
        this.setData({
          form: res.data.rows[0],
          'form.reason': '',
        });

      }
    });
  },

  confirm() {
    if (this.data.que == true ) {
      if (!!!this.data.form.room && this.data.form.subscribeType==2) {
        wx.showToast({
          title: '请选择房间',
          image: '../../assets/error.png',
        })
      } else {
        this.setData({
          ['form.status']: 1,
        })
        var personList = {
          url: '/system/subscribe/updateStatus',
          method: 'put',
          data: this.data.form
        }
        APP.request.backWxRequest(personList).then(res => {
          if (res.data.code === 200) {
            this.setData({
              form: [],
              paramas: '',
              pageNum: 1,
              pageSize: 4,
              navList: []
            });
            this.onShow();
          }
        });
      }

    } else if (this.data.jujue == true) {
      if (!!!this.data.form.reason) {
        wx.showToast({
          title: '请填写拒绝理由',
          image: '../../assets/error.png',
        })

      } else {
        this.setData({
          ['form.status']: 2,
        })
        var personList = {
          url: '/system/subscribe/updateStatus',
          method: 'put',
          data: this.data.form
        }
        APP.request.backWxRequest(personList).then(res => {
          if (res.data.code === 200) {
            wx.showToast({
              title: '成功！',
              image: '../../assets/success.png',
            })
            this.setData({
              form: [],
              paramas: '',
              pageNum: 1,
              pageSize: 4,
              navList: []
            });
        
    
            this.onShow();
          }
        });
      }

    } else if (this.data.sh == true) {
      if (!!!this.data.form.reason) {
        wx.showToast({
          title: '请填写申请理由',
          image: '../../assets/error.png',
        })
      } else {
        var personList = {
          url: '/system/subscribe/updateDelFlag',
          method: 'put',
          data: this.data.form
        }
        APP.request.backWxRequest(personList).then(res => {
          if (res.data.code === 200) {
            wx.showToast({
              title: '成功！',
              image: '../../assets/success.png',
            })
            this.setData({
              form: [],
              yuyueForm: [],
              daySelecter: [],
              timeRangeSelecter: [],
              paramas: '',
              pageNum: 1,
              pageSize: 4,
              navList: []
            });
            this.onShow();
          }
        });
      }

    } else if (this.data.quxiao == true) {
      if (!!!this.data.form.reason) {
        wx.showToast({
          title: '请填写取消理由',
          image: '../../assets/error.png',
        })
      } else {
        this.setData({
          ['form.status']: 3,
        })
        var personList = {
          url: '/system/subscribe/updateDelFlag',
          method: 'put',
          data: this.data.form
        }
        APP.request.backWxRequest(personList).then(res => {
          if (res.data.code === 200) {
            wx.showToast({
              title: '成功！',
              image: '../../assets/success.png',
            })
            this.setData({
              form: [],
              yuyueForm: [],
              daySelecter: [],
              timeRangeSelecter: [],
              paramas: '',
              pageNum: 1,
              pageSize: 4,
              navList: []
            });
            this.onShow();
          }
        });
      }

    }



  },


  //搜索
  onClick: function () {
    this.setData({
      pageNum: 1,
      pageSize: 4,
      navList: []
    })
    this.getList();
  },
  onChange(e) {

    this.setData({
      paramas: {
        userName: e.detail,
      }
    });
  },
  onSearch() {
    this.setData({
      pageNum: 1,
      pageSize: 4,
      navList: []
    })
    this.getList();
  },
  //记录
  jilu: function (detail) {
    this.setData({
      paramas: [],
      itemTitle: '选择日期'
    });
    console.log(detail.detail)
    this.setData({
      paramas: {
        timeNum: detail.detail
      }
    });
    this.setData({
      pageNum: 1,
      pageSize: 4,
      navList: []
    })
    this.getList();
  },
  //日期

  sure: function (event) {
    var date = event.detail
    this.setData({
      itemTitle: util.js_date_time(date),
      paramas: {
        createTime: util.js_date_time(date)
      }
    });
    this.setData({
      pageNum: 1,
      pageSize: 4,
      navList: []
    })
    this.getList();
    this.selectComponent('#item').toggle();
  },

  close: function () {
    this.selectComponent('#item').toggle();
  },
  cancel: function () {
    this.setData({
      yuyueForm: [],
      daySelecter: [],
      timeRangeSelecter: [],
      form: [],
      openPic: false,
    })
  },
  //日历弹出框
  showTime() {
    this.setData({
      show: false,
      showTime: true

    });
  },
  onClose() {
    this.setData({

      showTime: false,
      show: true,

    });
  },
  formatDate(date) {

    // date.bottomInfo = '选中';
    var month = date.getMonth() + 1
    if (+month < 10) {
      month = '0' + month
    }
    var day = date.getDate()
    console.log(day);

    if (+day < 10) {
      day = '0' + day
    }
    // return `${date.getFullYear()}-${month}-${date.getDate()}`;
    return `${date.getFullYear()}-${month}-${day}`;









    // // date.bottomInfo = '选中';
    // var month = date.getMonth() + 1
    // if (+month < 10) {
    //   month = '0' + month
    // }
    // return `${date.getFullYear()}-${month}-${date.getDate()}`;
    // // date.getMonth() + 1

    // // const month = day.date.getMonth() + 1;
    // // const date = day.date.getDate();
    // // if (day.type === 'start') {
    // //   day.bottomInfo = '选中';
    // // }

    // // return day;

  },
  //openDay    监听打开事件  打开日历组件
  openDay() {
    this.setData({
      timeRangeSelecter: [],
      timeActiveIndex: -1,
      'yuyueForm.timeDateStr': ''
    })
  },
  // 点击日期选择器的日期     做显示可选时间段范围判断
  selectDay(e) {
    this.setData({
      timeRangeSelecter: []
    })
    console.log('e', e.detail);

    console.log('日期格式化', this.formatDate(e.detail))
    this.setData({
      'yuyueForm.timeDate': this.formatDate(e.detail),
      'form.timeDate': this.formatDate(e.detail)

    })
    var date = this.formatDate(e.detail)
    var daySelecter = this.data.daySelecter
    // console.log(date);
    console.log(daySelecter);

    // 遍历  把时间一致的日期范围数据放到
    daySelecter.forEach((items, i) => {
      if (items.timeDateStr == date) {
        console.log(items.times)
        this.setData({
          timeRangeSelecter: items.times
        })
      }
    })
    console.log('日期范围数据', this.data.timeRangeSelecter);

  },
  //点击日期选择器的时间
  clickTime(e) {
    var index = e.target.dataset.index
    // console.log(index);
    var k = this.data.timeRangeSelecter[index].timeDateStr
    var a = k.split("-")
    console.log(a)
    this.setData({
      timeActiveIndex: index,
      'yuyueForm.timeDateStr': this.data.timeRangeSelecter[index].timeDateStr,
      'form.startTime': a[0],
      'form.endTime': a[1],
      'form.recoderId': this.data.timeRangeSelecter[index].recoderId

    })

  },
  onGotUserInfo: function (e) {
    let userInfo = e.detail.userInfo || {};
    // store data for next launch use
    wx.setStorage({
      key: 'userInfo',
      data: userInfo,
    })
    this.onJoin(userInfo);
  },
  /**
   * check if join is locked now, this is mainly to prevent from clicking join btn to start multiple new pages
   */
  checkJoinLock: function () {
    return !(this.lock || false);
  },

  lockJoin: function () {
    this.lock = true;
  },

  unlockJoin: function () {
    this.lock = false;
  },

  onJoin: function (userInfo) {
    userInfo = userInfo || {};
    let value = this.channel || "";

    let uid = this.uid;
    if (!value) {
      wx.showToast({
        title: '请提供一个有效的房间名',
        icon: 'none',
        duration: 2000
      })
    } else {
      var list = {
        url: '/system/subscribe/getVideoRoom/' + this.channel,
        method: 'get',

      }
      APP.request.backWxRequest(list).then(res => {

        if (res.data.code === 200) {
          if (this.checkJoinLock()) {
            this.lockJoin();
            if (value === "agora") {
              // go to test page if channel name is agora
              wx.navigateTo({
                url: `../test/test`
              });
            } else if (value === "agora2") {
              // go to test page if channel name is agora
              wx.navigateTo({
                url: `../test2/test2`
              });
            } else {
              let role = "audience";
              role = "broadcaster";
              wx.navigateTo({
                url: `../meeting/meeting?channel=${value}&uid=${uid}&role=${role}`
              });
            }
          }
        }
      });

    }
  },
  onInputChannel: function (e) {
    let value = e.detail.value;
    this.channel = value;
  }
})